package cn.hpclub.server.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.SalesPromotion;
import cn.hpclub.server.model.ServiceReservation;

public class OperateDataService extends Service{
    private static Logger            log     = LoggerFactory.getLogger(OperateDataService.class);
    public static OperateDataService service = new OperateDataService();

    public JSONArray queryOperateDataById(int dyid) throws ParseException{
        String sql = "SELECT DATE_FORMAT(time, '%Y-%m-%d') AS SaleDate, count(time) AS SaleAmount, moduleId FROM sales_promotion WHERE " +
                " business_code !='1895' AND userid = "
                + "?"
                + " AND appid = '100000056' AND DATE_FORMAT(time, '%Y-%m-%d') >= DATE_FORMAT( DATE_SUB(NOW(), INTERVAL 7 DAY), '%Y-%m-%d' ) AND return_code='0' GROUP BY SaleDate, moduleId;";
        String sqlKuandai = "SELECT DATE_FORMAT(create_date, '%Y-%m-%d') AS SaleDate, count(create_date) AS SaleAmount FROM service_reservation WHERE user_id = "
                + "?"
                + " AND appid = '100000056' AND service_type = 2 AND DATE_FORMAT(create_date, '%Y-%m-%d') >= DATE_FORMAT( DATE_SUB(NOW(), INTERVAL 7 DAY), '%Y-%m-%d' ) GROUP BY SaleDate;";

        String sqlTerminal = " SELECT DATE_FORMAT(create_time, '%Y-%m-%d') AS SaleDate,count(create_time) AS SaleAmount "
                + " FROM order_info WHERE sales_id = ? AND DATE_FORMAT(create_time, '%Y-%m-%d') >= DATE_FORMAT( DATE_SUB(NOW(), INTERVAL 7 DAY), '%Y-%m-%d' ) GROUP BY SaleDate;";

        List<Record> records = Db.find(sql, dyid);
        List<Record> kuandaiRecords = Db.find(sqlKuandai, dyid);
        List<Record> terminalRecords = Db.find(sqlTerminal, dyid);

        HashMap<String, Integer> hmJiaofei = new HashMap<>();
        HashMap<String, Integer> hmKaika = new HashMap<>();
        HashMap<String, Integer> hmXuanhao = new HashMap<>();
        HashMap<String, Integer> hmZifei = new HashMap<>();
        HashMap<String, Integer> hmBudengji = new HashMap<>();
        HashMap<String, Integer> hmYingxiao = new HashMap<>();
        HashMap<String, Integer> hmKuandai = new HashMap<>();
        HashMap<String, Integer> hmTerminal = new HashMap<>();

        for(Record data : records){
            if(data.getInt("moduleId") == Constant.ModuleID.JIAOFEI){
                hmJiaofei.put(data.getStr("SaleDate"), data.getLong("SaleAmount").intValue());
            } else if(data.getInt("moduleId") == Constant.ModuleID.KAIKA){
                hmKaika.put(data.getStr("SaleDate"), data.getLong("SaleAmount").intValue());
            } else if(data.getInt("moduleId") == Constant.ModuleID.XUANHAO){
                hmXuanhao.put(data.getStr("SaleDate"), data.getLong("SaleAmount").intValue());
            } else if(data.getInt("moduleId") == Constant.ModuleID.ZIFEI){
                hmZifei.put(data.getStr("SaleDate"), data.getLong("SaleAmount").intValue());
            } else if(data.getInt("moduleId") == Constant.ModuleID.BUDENGJI){
                hmBudengji.put(data.getStr("SaleDate"), data.getLong("SaleAmount").intValue());
            } else if(data.getInt("moduleId") == Constant.ModuleID.YINGXIAO){
                hmYingxiao.put(data.getStr("SaleDate"), data.getLong("SaleAmount").intValue());
            }
        }

        for(Record kuandai : kuandaiRecords){
            hmKuandai.put(kuandai.getStr("SaleDate"), kuandai.getLong("SaleAmount").intValue());
        }

        for(Record terminal : terminalRecords){
            hmTerminal.put(terminal.getStr("SaleDate"), terminal.getLong("SaleAmount").intValue());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date currentDate = new Date();

        JSONArray jaJiaofei = new JSONArray();
        JSONArray jaKaika = new JSONArray();
        JSONArray jaXuanhao = new JSONArray();
        JSONArray jaZifei = new JSONArray();
        JSONArray jaBudengji = new JSONArray();
        JSONArray jaYingxiao = new JSONArray();
        JSONArray jaKuandai = new JSONArray();
        JSONArray jaTerminal = new JSONArray();

        // 7天
        for(int i = 0; i < 7; i++){
            c.setTime(currentDate);
            c.add(Calendar.DATE, -i);
            String date = sdf.format(c.getTime());

            createOneDayItem(hmJiaofei, jaJiaofei, date);
            createOneDayItem(hmKaika, jaKaika, date);
            createOneDayItem(hmXuanhao, jaXuanhao, date);
            createOneDayItem(hmZifei, jaZifei, date);
            createOneDayItem(hmBudengji, jaBudengji, date);
            createOneDayItem(hmYingxiao, jaYingxiao, date);
            createOneDayItem(hmKuandai, jaKuandai, date);
            createOneDayItem(hmTerminal, jaTerminal, date);
        }

        JSONObject jsonResultJiaofei = createModuleItem(jaJiaofei, Constant.ModuleName.JIAOFEI,
                                                        Constant.ModuleID.JIAOFEI);
        JSONObject jsonResultKaika = createModuleItem(jaKaika, Constant.ModuleName.KAIKA, Constant.ModuleID.KAIKA);
        JSONObject jsonResultXuanhao = createModuleItem(jaXuanhao, Constant.ModuleName.XUANHAO,
                                                        Constant.ModuleID.XUANHAO);
        JSONObject jsonResultZifei = createModuleItem(jaZifei, Constant.ModuleName.ZIFEI, Constant.ModuleID.ZIFEI);
        JSONObject jsonResultBudengji = createModuleItem(jaBudengji, Constant.ModuleName.BUDENGJI,
                                                         Constant.ModuleID.BUDENGJI);
        JSONObject jsonResultYingxiao = createModuleItem(jaYingxiao, Constant.ModuleName.YINGXIAO,
                                                         Constant.ModuleID.YINGXIAO);
        JSONObject jsonResultKuandai = createModuleItem(jaKuandai, Constant.ModuleName.KUANDAI,
                                                        Constant.ModuleID.KUANDAI);

        JSONObject jsonResultTerminal = createModuleItem(jaTerminal, Constant.ModuleName.TERMINAL,
                                                         Constant.ModuleID.TERMINAL);

        JSONArray result = new JSONArray();
        result.put(jsonResultJiaofei);
        result.put(jsonResultKaika);
        result.put(jsonResultXuanhao);
        result.put(jsonResultZifei);
        result.put(jsonResultBudengji);
        result.put(jsonResultYingxiao);
        result.put(jsonResultKuandai);
        result.put(jsonResultTerminal);
        return result;
    }

    private JSONObject createModuleItem(JSONArray source, String moduleName, int moduleID){
        JSONObject reslut = new JSONObject();
        reslut.put("ListMdl", source);
        reslut.put("Name", moduleName);
        reslut.put("Type", moduleID);
        return reslut;
    }

    private void createOneDayItem(HashMap<String, Integer> source, JSONArray dest, String date){
        JSONObject json = new JSONObject();
        json.put("SaleDate", date);
        if(source.containsKey(date)){
            json.put("SaleAmount", source.get(date));
        } else{
            json.put("SaleAmount", 0);
        }
        dest.put(json);
    }

    public JSONArray queryAllOrderData(int dyid, int type, String starttime, String endtime){
        List<Record> records = null;
        if(type == Constant.ModuleID.KUANDAI){// 宽带预约订单
            records = ServiceReservation.dao.queryAllOrderData(dyid, starttime, endtime);
        } else if(type == Constant.ModuleID.TERMINAL){// 终端销售
            records = ServiceReservation.dao.queryAllTerminalOrderData(dyid, starttime, endtime);
        } else{
            records = SalesPromotion.dao.queryAllOrderData(dyid, type, starttime, endtime);
        }
        // log.info("records = " + records.toString());
        JSONArray jsonData = new JSONArray();
        HashMap<String, Integer> datas = new HashMap<>();
        for(Record r : records){
            datas.put(r.getStr(ClientApiConstant.Key.SALEDATE), r.getLong(ClientApiConstant.Key.SALEAMOUNT).intValue());
        }

        try{
            jsonData = createOtherDateData(datas, starttime, endtime);
        }
        catch(ParseException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return jsonData;
    }

    private JSONArray createOtherDateData(HashMap<String, Integer> datas, String starttime, String endtime)
            throws ParseException{
        int days = getDaysBetweenTwoDate(starttime, endtime);
        // log.info("daysBetweenTwoDate = " + days);
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdfFrom = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat sdfTo = new SimpleDateFormat("yyyy-MM-dd");
        JSONArray jsonData = new JSONArray();
        JSONObject object = null;
        for(int i = 0; i <= days; i++){
            object = new JSONObject();
            c.setTime(sdfFrom.parse(endtime));
            c.add(Calendar.DATE, -i);
            String date = sdfTo.format(c.getTime());
            object.put(ClientApiConstant.Key.SALEDATE, date);
            if(datas.containsKey(date)){
                object.put(ClientApiConstant.Key.SALEAMOUNT, datas.get(date));
            } else{
                object.put(ClientApiConstant.Key.SALEAMOUNT, 0);
            }
            jsonData.put(object);
        }
        // log.info("jsonData = " + jsonData.toString());
        return jsonData;
    }

    private int getDaysBetweenTwoDate(String starttime, String endtime) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(starttime));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(endtime));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    public JSONArray queryRankListByStoreId(int storeId){
        String sql = "SELECT id, MasterName, sum(SaleCount) AS SaleCount FROM ( SELECT u.id AS id, u. NAME AS MasterName, count(userid) AS SaleCount FROM ( SELECT mo.id, mo. NAME, sp.userid FROM member_org mo LEFT JOIN sales_promotion sp ON mo.id = sp.userid AND DATE_FORMAT(sp.time, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') WHERE mo.org_id = "
                + "?"
                + " AND member_type = 2 ) AS u GROUP BY u.id UNION ALL SELECT u.id AS id, u. NAME AS MasterName, count(userid) AS SaleCount FROM ( SELECT mo.id, mo. NAME, sr.user_id AS userid FROM member_org mo LEFT JOIN service_reservation sr ON mo.id = sr.user_id AND DATE_FORMAT(sr.create_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') WHERE mo.org_id = "
                + "?" + " AND member_type = 2 ) AS u GROUP BY u.id ) AS c GROUP BY id ORDER BY id ASC;";
        List<Record> records = Db.find(sql, storeId, storeId);

        JSONArray resultJsonArray = new JSONArray();
        for(Record record : records){
            JSONObject json = new JSONObject();
            json.put("StoreMasterID", record.getInt("id"));
            json.put("MasterName", record.getStr("MasterName"));
            json.put("SaleCount", record.getBigDecimal("SaleCount").intValue());

            resultJsonArray.put(json);
        }

        return resultJsonArray;
    }

}
